package com.hltx.controller.app.business;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hltx.constants.PayConstant;
import com.hltx.controller.base.BaseController;
import com.hltx.pojo.business.BusinessInfo;
import com.hltx.pojo.common.Page;
import com.hltx.pojo.pay.PayInfo;
import com.hltx.service.business.BusinessManager;
import com.hltx.util.CustomUtil;
import com.hltx.util.DataUtil;
import com.hltx.util.DateUtil;
import com.hltx.util.MessagesCode;
import com.hltx.util.ResultInfo;

@Controller
@RequestMapping(value = "/app/business/")
public class AppBusinessHandelController extends BaseController {
     
	
	@Resource(name = "businessService")
	private BusinessManager businessService;

	@Value("${domain}")
	private String domain;
	
	@RequestMapping(value = "/placePayOrderMoney", method = { RequestMethod.POST,RequestMethod.GET })
	@ResponseBody
	public Map<String,Object> placePayOrderMoney(PayInfo pi,
			HttpServletRequest request){
		this.logBefore(logger, "商家生成支付订单（金钱支付）-开始");
		Map<String, Object> resMap = new HashMap<String, Object>();
		try{
			BigDecimal price = pi.getTotalPrice();
			if(price == null || price.compareTo(BigDecimal.ZERO)<=0){
				resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.PRICE_ERROR, "金额错误"));
				return resMap;
			}
			
			//查询商户是否存在
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("businessId", pi.getBusinessId());
			params.put("userId", pi.getUserId());
			BusinessInfo bi = businessService.getBusinessInfo(params);
			if(bi == null){
				resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.BUSINESS_EXIST, "商户不存在"));
			}else{
				//生成支付订单
				PayInfo pin = new PayInfo();
				pin.setCodePre(DateUtil.getYear());
				pin.setCodeSuf(CustomUtil.codeSuf(3, pi.getBusinessId()));
				pin.setBusinessId(pi.getBusinessId());
				pin.setUserId(0);
				pin.setPayMode("");
				pin.setRemark(pi.getRemark());
				pin.setTotalPointsNum(0);
				pin.setAddPrice(BigDecimal.ZERO);
				pin.setBalancePrice(BigDecimal.ZERO);
				pin.setTotalPrice(pi.getTotalPrice());
				pin.setState(PayConstant.PAY_WAIT);
				pin.setLine(PayConstant.LINE_DOWN);
				pin.setType(PayConstant.PAY_TYPE_DOWN_1);
				pin.setCreateTime(DateUtil.getTime());
				
				businessService.addBussinessPayInfo(pin);
				resMap.put("payCode", CustomUtil.strAppend(pin.getCodePre(),pin.getId(),pin.getCodeSuf()));
				resMap.put("price", pin.getTotalPrice());
				resMap.put("headPhoto", bi.getHeadPhoto());
				resMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", ""));

			}
			
			
		}catch(Exception e){
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
		}
		this.logAfter(logger);
		return resMap;
	}
	
	@RequestMapping(value = "/placePayOrderPoints", method = { RequestMethod.POST,RequestMethod.GET })
	@ResponseBody
	public Map<String,Object> placePayOrderPoints(PayInfo pi,
			HttpServletRequest request){
		this.logBefore(logger, "商家生成支付订单（兑换券支付）-开始");
		Map<String, Object> resMap = new HashMap<String, Object>();
		try{
			BigDecimal price = DataUtil.getBigDecimal(pi.getTotalPrice()) ;
			int totalPointsNum = pi.getTotalPointsNum();
			if(totalPointsNum <= 0){
				resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.PRICE_ERROR, "兑换券错误"));
				return resMap;
			}
			
			//查询商户是否存在
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("businessId", pi.getBusinessId());
			params.put("userId", pi.getUserId());
			BusinessInfo bi = businessService.getBusinessInfo(params);
			if(bi == null){
				resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.BUSINESS_EXIST, "商户不存在"));
			}else{
				//生成支付订单
				BigDecimal totalPrice = price.add(DataUtil.getBigDecimal(totalPointsNum));
				PayInfo pin = new PayInfo();
				pin.setCodePre(DateUtil.getYear());
				pin.setCodeSuf(CustomUtil.codeSuf(3, pi.getBusinessId()));
				pin.setBusinessId(pi.getBusinessId());
				pin.setUserId(0);
				pin.setPayMode("");
				pin.setRemark(pi.getRemark());
				pin.setTotalPointsNum(totalPointsNum);
				pin.setAddPrice(BigDecimal.ZERO);
				pin.setBalancePrice(BigDecimal.ZERO);
				pin.setTotalPrice(totalPrice);
				pin.setState(PayConstant.PAY_WAIT);
				pin.setLine(PayConstant.LINE_DOWN);
				pin.setType(PayConstant.PAY_TYPE_DOWN_2);
				pin.setCreateTime(DateUtil.getTime());
				
				businessService.addBussinessPayInfo(pin);
				resMap.put("payCode", CustomUtil.strAppend(pin.getCodePre(),pin.getId(),pin.getCodeSuf()));
				resMap.put("price", pi.getTotalPrice());
				resMap.put("points", pin.getTotalPointsNum());
				resMap.put("headPhoto", bi.getHeadPhoto());
				resMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", ""));
			}
			
			
		}catch(Exception e){
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
		}
		this.logAfter(logger);
		return resMap;
	}	
	
	@RequestMapping(value = "/getPayList", method = { RequestMethod.POST,RequestMethod.GET })
	@ResponseBody
	public Map<String,Object> getPayList(Page page,@RequestParam("businessId") int businessId, HttpServletRequest request){
		this.logBefore(logger, "查询商户收款明细-开始");
		Map<String, Object> resMap = new HashMap<String, Object>();
		try{

			if(businessId <=0){
				resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.PARAMS_ERROR, "参数错误"));
				return resMap;
			}
			int start = (page.getPage()-1) * page.getShowNumber();
			
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("businessId", businessId);
			params.put("start", start);
			params.put("state", PayConstant.PAY_SUCCESS);
			params.put("showNumber", page.getShowNumber());
			
			List<Map<String, Object>> piList = businessService.getBusColListByBusId(params);
			
			resMap.put("piList", piList);
			resMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", ""));
			
		}catch(Exception e){
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
		}
		
		
		return resMap;
	}
	
	
	@RequestMapping(value = "/getPayInfo", method = { RequestMethod.POST,RequestMethod.GET })
	@ResponseBody
	public Map<String,Object> getPayInfo(String payCode, HttpServletRequest request){
		this.logBefore(logger, "查询商户账单详情-开始");
		Map<String, Object> resMap = new HashMap<String, Object>();
		try{

			if(StringUtils.isEmpty(payCode) || StringUtils.length(payCode)<12){
				resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.PARAMS_ERROR, "参数错误"));
				return resMap;
			}
			int len = payCode.length();
			String codePre = payCode.substring(0, 4);
    		String codeSuf = payCode.substring(len - 7);
    		long payId = Long.parseLong(payCode.substring(4, len - 7));
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("payId", payId);
			params.put("codePre", codePre);
			params.put("codeSuf", codeSuf);
			Map<String, Object> payInfo = businessService.getPayInfoById(params);
			
			int businessId = (int)payInfo.get("businessId");
			params.clear();
			params.put("businessId", businessId);
			BusinessInfo bi = businessService.getBusinessInfo(params);
			BigDecimal price = (BigDecimal)payInfo.get("totalPrice");
			int pointsNum = (int)payInfo.get("pointsNum");
			price = price.subtract(DataUtil.getBigDecimal(pointsNum));
			payInfo.put("price", price);
			resMap.put("payInfo", payInfo);
			resMap.put("bi", bi);
			resMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", ""));
			
		}catch(Exception e){
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
		}
		
		
		return resMap;
	}
	
	@RequestMapping(value = "/toGenPayPage", method = { RequestMethod.POST,RequestMethod.GET })
	@ResponseBody
	public Map<String,Object> toGenPayPage(String payCode, HttpServletRequest request){
		this.logBefore(logger, "去支付界面-开始");
		Map<String, Object> resMap = new HashMap<String, Object>();
		try{

			if(StringUtils.isEmpty(payCode) || StringUtils.length(payCode)<12){
				resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.PARAMS_ERROR, "参数错误"));
				return resMap;
			}
			int len = payCode.length();
			String codePre = payCode.substring(0, 4);
			String codeSuf = payCode.substring(len - 7);
			long payId = Long.parseLong(payCode.substring(4, len - 7));
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("payId", payId);
			params.put("codePre", codePre);
			params.put("codeSuf", codeSuf);
			Map<String, Object> payInfo = businessService.getPayInfoById(params);
			System.out.println(payInfo);
			int businessId = (int)payInfo.get("businessId");
			params.clear();
			params.put("businessId", businessId);
			BusinessInfo bi = businessService.getBusinessInfo(params);
			BigDecimal price = (BigDecimal)payInfo.get("totalPrice");
			int pointsNum = (int)payInfo.get("pointsNum");
			price = price.subtract(DataUtil.getBigDecimal(pointsNum));
			payInfo.put("price", price);
			resMap.put("payInfo", payInfo);
			resMap.put("bi", bi);
			resMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", ""));
			
		}catch(Exception e){
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
		}
		
		
		return resMap;
	}	
	
	
	@RequestMapping(value = "/toPrePayPage", method = { RequestMethod.POST,RequestMethod.GET })
	@ResponseBody
	public Map<String,Object> toPrePayPage(@RequestParam("businessId") int businessId, HttpServletRequest request){
		this.logBefore(logger, "去预支付界面-开始");
		Map<String, Object> resMap = new HashMap<String, Object>();
		try{

			if(businessId <=0){
				resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.PARAMS_ERROR, "参数错误"));
				return resMap;
			}

			Map<String, Object> params = new HashMap<String, Object>();

			params.put("businessId", businessId);
			BusinessInfo bi = businessService.getBusinessInfo(params);
			
			resMap.put("bi", bi);
			resMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", ""));
			
		}catch(Exception e){
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
		}
		
		
		return resMap;
	}
	
	@RequestMapping(value = "/updatePayInfoState", method = { RequestMethod.POST,RequestMethod.GET })
	@ResponseBody
	public Map<String, Object> updatePayInfoState (HttpServletResponse response, HttpServletRequest request) {
		this.logBefore(logger, "修改支付信息状态为已取消");
		Map<String, Object> resMap = new HashMap<String, Object>();
		String payCode = request.getParameter("payCode");
		int len = StringUtils.length(payCode);
		try{
			String codePre=payCode.substring(0, 4);
			String codeSuf=payCode.substring(len - 7);
			long payId = Long.parseLong(payCode.substring(4, len - 7));
		
			Map<String, Object> payParams = new HashMap<String, Object>();
			payParams.put("payId", payId);
			payParams.put("codePre", codePre);
			payParams.put("codeSuf", codeSuf);
			payParams.put("state", PayConstant.PAY_CANCEL);
			Map<String, Object> payInfo = businessService.getPayInfoById(payParams);
			
			if(payInfo == null){
				resMap.put("result", this.initResult(ResultInfo.ERROR, "error", "该单不存在"));
				return resMap;
			}
			
			String payState = (String)payInfo.get("state");
			
			if(StringUtils.equals(payState, PayConstant.PAY_SUCCESS) ||
					StringUtils.equals(payState, PayConstant.PAY_CANCEL)){
				resMap.put("result", this.initResult(ResultInfo.ERROR, "error", "该单已支付或已取消"));
				return resMap;
			}
			businessService.updatePayInfoState(payParams);
			resMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", "修改支付信息状态成功"));
		}catch(Exception e){
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
		}
		return resMap;
	}
}
